from apscheduler.schedulers.blocking import BlockingScheduler
import backtrader as bt
import baostock as bs
import datetime
from config import COIN_TARGET
from nowMysqlStrategies.MysqSM25Bias import MysqSM25Bias
from nowMysqlStrategies.dataInput import dataInput
from nowMysqlStrategies.nowMysqlKeyPointsStrategy import nowMysqlKeyPointsStrategy
from nowMysqlStrategies.nowMysqlTimeBehindtrategy import nowMysqlTimeBehindtrategy

# 基本日线数据写入
from util.GetBaostockDat import GetBaostockDat


def dataInputSql():
     d = dataInput()
     d.sql()
# 复权因子写入
def dataInputFqyz():
     d = dataInput()
     d.fqyz()

# 右侧
def dataInputYouce():
     try:
          print("右侧开始运行!")
          fromdate = datetime.datetime(2020, 1, 1)
          todate = datetime.datetime(2022, 2, 20)
          lg = bs.login(user_id='anonymous', password='123456')
          '''
          lg = bs.login(user_id='anonymous', password='123456')
          # 获取中证500成分股
          rs = bs.query_all_stock(day='%s-%s-%s' % (datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day - 1))
          # bs.query_hs300_stocks()  # query_hs300_stocks()  query_zz500_stocks()
          while (rs.error_code == '0') & rs.next():
                    code = rs.get_row_data()[0]
                    # print(code)
                    if ("bj" in code) == False:
                         cerebro = bt.Cerebro(quicknotify=True)
                         data = '2020-01-01'
                         data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, False)
                         cerebro.adddata(data, name=code)
                         broker = cerebro.getbroker()
                         broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                         broker.setcash(10000.0)  #
                         cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                         cerebro.addstrategy(nowMysqlTimeBehindtrategy)
                         cerebro.run()
               except Exception as err:
                    1 + 1
          '''
          rs = bs.query_hs300_stocks()  # query_hs300_stocks()  query_zz500_stocks()
          while (rs.error_code == '0') & rs.next():

                    cerebro = bt.Cerebro(quicknotify=True)
                    d = rs.get_row_data()
                    code = d[1]
                    data = '2020-01-01'
                    h = datetime.datetime.now().hour
                    if h > 8 and h < 19:
                         v = True
                    else:
                         v = False
                    data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, v)
                    # data = GetTushareDat().getData(pro,stk_code, data, 'w', fromdate, todate)
                    cerebro.adddata(data, name=code)
                    broker = cerebro.getbroker()
                    broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                    broker.setcash(10000.0)  #
                    cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                    cerebro.addstrategy(nowMysqlTimeBehindtrategy)
                    cerebro.run()
     except Exception as err:
          1 + 1
          print("Finished with error: ", err)
     print("运行完成!")

     print("右侧运行结束!")


#SM25Bias
def SM25Bias():
     try:
          fromdate = datetime.datetime(2020, 1, 1)
          todate = datetime.datetime(2022, 2, 20)
          lg = bs.login(user_id='anonymous', password='123456')
          '''
          print("SM25Bias开始运行!")
          fromdate = datetime.datetime(2020, 1, 1)
          todate = datetime.datetime(2022, 2, 20)
          lg = bs.login(user_id='anonymous', password='123456')
          # 获取中证500成分股
          rs = bs.query_all_stock(day='%s-%s-%s' % (datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day - 1))
          # bs.query_hs300_stocks()  # query_hs300_stocks()  query_zz500_stocks()
          while (rs.error_code == '0') & rs.next():
               try:
                    code = rs.get_row_data()[0]
                    # print(code)
                    if ("bj" in code) == False:
                         cerebro = bt.Cerebro(quicknotify=True)
                         data = '2020-01-01'
                         h=datetime.datetime.now().hour
                         if h > 8  and  h < 19 :
                              v = True
                         else:
                              v = False
                         data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, v)
                         cerebro.adddata(data, name=code)
                         broker = cerebro.getbroker()
                         broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                         broker.setcash(10000.0)  #
                         cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                         cerebro.addstrategy(MysqSM25Bias)
                         cerebro.run()
               except Exception as err:
                    1 + 1
          print("SM25Bias运行结束!")
          '''
          print("SM25Bias开始运行!")
          rs = bs.query_hs300_stocks()  # query_hs300_stocks()  query_zz500_stocks()
          while (rs.error_code == '0') & rs.next():

                    cerebro = bt.Cerebro(quicknotify=True)
                    d = rs.get_row_data()
                    code = d[1]
                    data = '2020-01-01'
                    h = datetime.datetime.now().hour
                    if h > 8 and h < 19:
                         v = True
                    else:
                         v = False
                    data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, v)
                    # data = GetTushareDat().getData(pro,stk_code, data, 'w', fromdate, todate)
                    cerebro.adddata(data, name=code)
                    broker = cerebro.getbroker()
                    broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                    broker.setcash(10000.0)  #
                    cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                    cerebro.addstrategy(MysqSM25Bias)
                    cerebro.run()
     except Exception as err:
        1 + 1
        print ( "Finished with error: ", err )
     print ( "运行完成!" )







def KeyPoints():
     try:
          print("关键点开始运行!")
          fromdate = datetime.datetime(2020, 1, 1)
          todate = datetime.datetime(2022, 2, 20)
          lg = bs.login(user_id='anonymous', password='123456')
          '''
          lg = bs.login(user_id='anonymous', password='123456')
          rs = bs.query_all_stock(day='%s-%s-%s' % (
          datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day - 1))
          while (rs.error_code == '0') & rs.next():
               
                    code = rs.get_row_data()[0]
                    if ("bj" in code) == False:
                         cerebro = bt.Cerebro(quicknotify=True)
                         data = '2020-01-01'
                         h = datetime.datetime.now().hour
                         if h > 8 and h < 17:
                              v = True
                         else:
                              v = False
                         data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, v)
                         cerebro.adddata(data, name=code)
                         broker = cerebro.getbroker()
                         broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                         broker.setcash(10000.0)  #
                         cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                         cerebro.addstrategy(MysqlKeyPointsStrategy)
                         cerebro.run()
               except Exception as err:
                    1 + 1
          '''
          rs = bs.query_hs300_stocks()  # query_hs300_stocks()  query_zz500_stocks()
          while (rs.error_code == '0') & rs.next():

                    cerebro = bt.Cerebro(quicknotify=True)
                    d = rs.get_row_data()
                    code = d[1]
                    data = '2020-01-01'
                    h = datetime.datetime.now().hour
                    if h > 8 and h < 19:
                         v = True
                    else:
                         v = False
                    data = GetBaostockDat().getData(bs, code, data, 'd', fromdate, todate, v)
                    # data = GetTushareDat().getData(pro,stk_code, data, 'w', fromdate, todate)
                    cerebro.adddata(data, name=code)
                    broker = cerebro.getbroker()
                    broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
                    broker.setcash(10000.0)  #
                    cerebro.addsizer(bt.sizers.FixedSize, stake=10)  # 设定需要设定每次交易买入的股数
                    cerebro.addstrategy(nowMysqlKeyPointsStrategy)
                    cerebro.run()
     except Exception as err:
          1 + 1
          print("Finished with error: ", err)
     print("关键点运行结束!")


if __name__ == '__main__':
     scheduler = BlockingScheduler ( )
     #  周一到周五，也可以写成 1-5 ，时间 18:30 ，ars：方法 notify入参；每周-到周五下午六点半执行notify方法
     scheduler.add_job ( dataInputSql, 'cron', day_of_week='mon-fri',misfire_grace_time=3600,  hour=17, minute=50 )
     scheduler.add_job ( dataInputFqyz, 'cron', month='4,5,7,8,10,11,1,2', misfire_grace_time=3600, day='1', hour=8, minute=5 )
     # 周一到周五  当前右侧机会
     scheduler.add_job ( dataInputYouce, 'cron', day_of_week='mon-fri', misfire_grace_time=3600, hour=19, minute=30 )
     #尾盘
     scheduler.add_job ( SM25Bias, 'cron', day_of_week= 'mon-fri', misfire_grace_time=3600, hour=14, minute=1 )
     scheduler.add_job ( KeyPoints, 'cron', day_of_week= 'mon-fri', misfire_grace_time=3600, hour=13, minute=12 )
     scheduler.start ( )